package com.scut.scutzone.interceptor;

import com.scut.scutzone.config.HttpSessionAttribute;
import com.scut.scutzone.exception.BusinessException;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author: lifeng Chan
 * @date: 2021/4/28 14:30
 * @description:
 * 检查登录情况，这里只需要覆写preHandle即可
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws BusinessException{

        HttpSession session= request.getSession();
        final String REQUEST_METHOD=request.getMethod();
        //按照zekai写的逻辑，判断会话请求方法不是OPTIONS,且会话路径不是创建用户和登陆页面，则不需要拦截，否则，抛出401错误
        //按照前后端分离的逻辑，前端收到401后再跳转到登录页面

        //拦截器拦截路径在拦截配置器中配置，这里就不配置
        if(!HttpMethod.OPTIONS.matches(REQUEST_METHOD) ){
            if(session.getAttribute(HttpSessionAttribute.USER_UUID)==null){
                throw new BusinessException(401,"请先登录");
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
